/*
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package jchess.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import jchess.server.Server;

/**
 *
 * @author MarioX
 */

public class SClient implements Runnable //connecting client
{
    private Socket s;
    public ObjectInputStream input;
    public ObjectOutputStream output;
    public String nick;
    private Table table;

    SClient(Socket s, ObjectInputStream input, ObjectOutputStream output, String nick, Table table)
    {
        this.s = s;
        this.input = input;
        this.output = output;
        this.nick = nick;
        this.table = table;

        Thread thread = new Thread(this);
        thread.start();
    }

    public void run() //listening
    {
        Server.print("running function: run()");
        boolean isOK = true;
        while(isOK)
        {
            try
            {
                String in = input.readUTF();

                if(in.equals("#move"))//new move
                {
                    int bX = input.readInt();
                    int bY = input.readInt();
                    int eX = input.readInt();
                    int eY = input.readInt();

                    table.sendMoveToOther(this, bX, bY, eX, eY);
                }
                if(in.equals("#message"))//new message
                {
                    String str = input.readUTF();

                    table.sendMessageToAll(nick + ": " + str);
                }
            }
            catch (IOException ex)
            {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                isOK = false;
                try
                {
                    table.sendErrorConnectionToOther(this);
                } catch (IOException ex1)
                {
                    Logger.getLogger(SClient.class.getName()).log(Level.SEVERE, null, ex1);
                }
            }

        }
    }
}